﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CL2036.PublicFunction
{
    internal class CLT
    {
        /// <summary>
        /// CLT11协议组帧
        /// </summary>
        /// <param name="myID"></param>
        /// <param name="toID"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] GetFrameData(byte myID, byte toID, byte[] data)
        {

            byte length = (byte)(4 + data.Length + 1);//包头+包 体+校验码
            ByteBuffer buf = new ByteBuffer();
            buf.Put(0x81);
            buf.Put(myID);
            buf.Put(toID);
            buf.Put(length);
            buf.Put(data);
            byte[] tmpData = buf.ToByteArray();
            byte chkSum = GetChkSum(tmpData);
            buf.Put(chkSum);
            return buf.ToByteArray();
        }

        /// <summary>
        /// 老版本协议组帧
        /// </summary>
        /// <param name="toID"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] GetFrameData(byte toID, byte[] data)
        {
            byte length = (byte)(3 + data.Length + 1);//包头+包 体+校验码
            ByteBuffer buf = new ByteBuffer();
            buf.Put(0x81);
            buf.Put(toID);
            buf.Put(length);
            buf.Put(data);
            byte[] tmpData = buf.ToByteArray();
            byte chkSum = GetChkSum(tmpData);
            buf.Put(chkSum);
            return buf.ToByteArray();
        }
        /// <summary>
        /// 计算检验码
        /// </summary>
        /// <param name="bytData"></param>
        /// <returns></returns>
        public static byte GetChkSum(byte[] bytData)
        {
            byte bytChkSum = 0;
            for (int int_Inc = 1; int_Inc < bytData.Length; int_Inc++)
            {
                bytChkSum ^= bytData[int_Inc];
            }
            return bytChkSum;
        }

    }
}
